﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;
using WYJ.SDK.Web;

namespace WebHelper.Controllers
{

    [ApiController]
    [Route("User")]
    public class UserController : Controller    
    {

        [HttpPost("Login")]
        public Response<User> Login(User user)
        {
            using var db = new DB();
            //List<User> users = db.Users.Query().ToList();
            //List<Book> books = db.Books.Query().ToList();
            var Exists = db.Users.Query().Where(x => x.Name == user.Name && x.Password == user.Password).FirstOrDefault();
            if (Exists == null) return Response<User>.Fail("用户名或密码不正确");
            return LoginSuccess(Exists);
        }

        [HttpGet("Logout")]
        public Response<string> Logout()
        {
            Response.Cookies.Append("token", "");
            //Response.Redirect("/");
            return Response<string>.Success(null);
        }

        private Response<User> LoginSuccess(User Exists)
        {
            Response.Cookies.Append("token", new Token()
            {
                NId = Exists.Id,
                Name = Exists.Name,
                SId = Exists.Email
            }.ToString(), new CookieOptions
            {
                HttpOnly = true,
                Secure = true,
                SameSite = SameSiteMode.None,
                Path = "/",
                Expires = DateTimeOffset.Now.AddDays(30)
            });
            return Response<User>.Success(Exists);
        }

        [HttpPost("Signin")]
        public Response<User> Signin(User user)
        {
            using var db = new DB();
            var Exists = db.Users.Query().Where(x => x.Name == user.Name).Exists();
            if (Exists) return Response<User>.Fail("用户名已存在");
            db.Users.Insert(user);
            return LoginSuccess(user);
        }

        [HttpGet("DeleteUser")]
        public Response<User> DeleteUser()
        {
            string? t = Request.Cookies["token"]?.ToString();
            if( t == null || !Token.TryParse(t, out var Exists)) return Response<User>.Fail();
            using var db = new DB();
            if(db.Users.Delete(Exists.NId)) return Response<User>.Success(null);
            return Response<User>.Fail();
        }

    }
}
